using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Weber.CS3280.Inventory.Logic;
using Weber.CS3280.Inventory.UI.Controls;
using Weber.CS3280.Inventory.UI.Windows;
using Weber.CS3280.UI.ViewModels;

namespace Weber.CS3280.Inventory.UI.ViewModels
{
	public class ItemCategoryViewModel : ItemDetailViewModelBase
	{
		private ItemCategoryController _itemCategory;

		/// <summary>
		/// Default constructor for use with a new ItemCategory
		/// </summary>
		public ItemCategoryViewModel()
			: this(new ItemCategoryController())
		{
		}

		/// <summary>
		/// Constructor that will construct an existing ItemCategoryController for an existing item
		/// </summary>
		/// <param name="itemCategory">Reference to the ItemCategoryController</param>
		public ItemCategoryViewModel(ItemCategoryController itemCategory)
		{
			_itemCategory = itemCategory;
			_itemCategory.PropertyChanged += _itemCategory_PropertyChanged;
			WindowTitle = "Edit Item Category";
		}

		/// <summary>
		/// Copy constructor for UI
		/// </summary>
		/// <param name="source">Source ItemCategoryViewModel</param>
		private ItemCategoryViewModel(ItemCategoryViewModel source)
			: this(source._itemCategory.Clone())
		{
		}

		void _itemCategory_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
		{
			NotifyPropertyChanged(e.PropertyName);
		}

		public int? ItemCategoryId
		{
			get { return _itemCategory.ItemCategoryId; }
		}

		public string Name
		{
			get { return _itemCategory.Name; }
			set { _itemCategory.Name = value; }
		}

		public override bool IsDirty
		{
			get { return _itemCategory.IsDirty; }
			set { _itemCategory.IsDirty = value; }
		}

		protected override bool Validate()
		{
			if (string.IsNullOrEmpty(Name))
				return false;

			return true;
		}

		protected override string BuildErrorMessage()
		{
			StringBuilder builder = new StringBuilder();

			if (string.IsNullOrEmpty(Name))
				builder.AppendLine("* Please specify a category name");

			return builder.ToString();
		}

		public override void Save()
		{
			using (Data.InventoryConnectionContext context = new Data.InventoryConnectionContext())
				_itemCategory.Save(context);
		}

		protected override void Edit(System.Windows.Controls.Control control)
		{
			EditControlHostWindow.ShowWindow<ItemCategoryDetailsControl>(new ItemCategoryViewModel(this), Window.GetWindow(control));
		}
	}
}
